<?php

namespace App\Http\Controllers;

use App\Comment;
use App\Formitem;
use App\FY\FeiyuApi;
use App\Keep;
use App\Likes;
use App\Message;
use App\Form;
use App\SMS\SendTemplateSMS;
use App\TagGroup;
use App\Post;
use App\Postmeta;
use App\Tag;
use App\User;
use App\Usermeta;
use App\Xcx\WXBizDataCrypt;
use Symfony\Component\HttpFoundation\Request;
use QrCode;

// add log lib
use Illuminate\Support\Facades\Log;

class XcxApi extends Controller{
    private function SessionKey(){
        $chaRid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = substr($chaRid, 0, 8).$hyphen
            .substr($chaRid, 8, 4).$hyphen
            .substr($chaRid,12, 4).$hyphen
            .substr($chaRid,16, 4).$hyphen
            .substr($chaRid,20,12);
        return $uuid;
    }
    private function getQR($id){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxfca50078ea0ff5c1&secret=845bd4e72e18887e19170550c49af3ed';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $json = curl_exec($ch);
        curl_close($ch);
        $json = json_decode($json);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$json->access_token;
        $post_data = array ("path" => "pages/view/view?id=".$id."&&type=active","width" => 430);
        $post_data = json_encode($post_data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }else{
            file_put_contents("upload/view/$id.jpg", $tmpInfo);
            return asset("upload/view/$id.jpg");
        }
    }
    private function createQR($user_id){
        $key = $this->SessionKey();
        $meta = Usermeta::where("user_id",$user_id)->where("key","QRCode")->first();
        if(!$meta){
            $meta = new Usermeta();
        }
        $meta->user_id = $user_id;
        $meta->key = 'QRCode';
        $meta->value = $key;
        if($meta->save()){
            QrCode::format('png')->size(300)->generate($key,public_path('upload/user/'.$user_id.'.png'));
            $meta = Usermeta::where("user_id",$user_id)->where("key","QR")->first();
            if(!$meta){
                $meta = new Usermeta();
            }
            $meta->user_id = $user_id;
            $meta->key = 'QR';
            $meta->value = asset('upload/user/'.$user_id.'.png');
            return $meta->save();
        }
        return 0;

    }
    private function RandomString()
    {
        $characters = '0123456789';
        $rand = '';
        for ($i = 0; $i < 6; $i++) {
            $rand = $rand.$characters[rand(0, 9)];
        }
        return $rand;
    }
    private function TimeStatus($now,$id){
        $start = Postmeta::where("post_id",$id)->where("key","activeTime")->first();
        $status = 0;
        if($start){
            if(strtotime($start->value)>$now){
                $status = 1;
            }else{
                $end = Postmeta::where("post_id",$id)->where("key","endTime")->first();
                if($end){
                    if(strtotime($end->value)>$now) {
                        $status = 2;
                    }
                }
            }
        }
        return $status;
    }
    public function WxLogin(Request $request){
        $data = $request->input();
        $code = $data['code'];
        if($code==='skXcx'){
            $appID = 'wxfca50078ea0ff5c1';
            $appSecret = '845bd4e72e18887e19170550c49af3ed';
            $js_code = $data['js_code'];
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appID.'&secret='.$appSecret.'&js_code='.$js_code.'&grant_type=authorization_code';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            $json = curl_exec($ch);

            curl_close($ch);
	    
	    Log::debug(json_encode($json));
            
	    $json = json_decode($json);
            $session = '';
            $session_time = '';
            $user_id = 0;
            $user_level = 0;
            $QR = '';
            if ( !isset($json->errcode) ){
                $session_key = $json->session_key;
                $User = User::where("openid",$json->openid)->first();
                $session = $this->SessionKey();
                $session_time = time()+604800;
                if($User){
                    $user_id = $User->id;
                    $user_level = $User->level;
                    $User->session = $session;
                    $User->session_time = $session_time;
                    $meta = Usermeta::where("user_id",$user_id)->where("key","QR")->first();
                    if(!$meta){
                        $QR = $this->createQR($user_id);
                    }else{
                        $QR = $meta->value;
                    }
                    if(!$User->save()){
                        return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
                    }
                }else{
                    $encryptedData = $data['encryptedData'];
                    $encryptedData = preg_replace('/\%2B/','+',$encryptedData);
                    $iv = $data['iv'];
                    if($iv&&$encryptedData){
                        $pc = new WXBizDataCrypt($appID, $session_key);
                        $errCode = $pc->decryptData($encryptedData, $iv, $data );
                        if(!$errCode){
                            $json = json_decode($data);
                            $open_id = $json->openId;
                            $User = User::where("openid",$open_id)->first();
                            if(!$User){
                                $randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
                                $rand = substr($randStr,0,6);

                                $User = new User();
                                $User->name = $json->nickName;
                                $User->password = bcrypt($rand);
                                $User->openid = $open_id;
                                $User->session = $session;
                                $User->session_time = $session_time;

                                if($User->save()){
                                    $avatar = $json->avatarUrl;
                                    $UserMeta =  new Usermeta();
                                    $UserMeta->user_id = $User->id;
                                    $UserMeta->key = 'avatar';
                                    $UserMeta->value = $avatar;
                                    $UserMeta->save();
                                    $user_id = $User->id;
                                    $QR = $this->createQR($user_id);
                                }else{
                                    return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
                                }
                            }
                        }
                    }
                }
            }
            return '{"user_id":'.$user_id.',"user_level":'.$user_level.',"session":"'.$session.'","session_time":"'.$session_time.'","QR":"'.$QR.'"}';
        }
        return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
    }
    public function GetSession(Request $request){
        $data = $request->input();
        $code = $data['code'];
        if($code==='sessionXcx'){
            $session = $data['session'];
            $User = User::where("session",$session)->first();
            $session_time = time();
            $user_id = 0;
            $user_level = 0;
            $session = '';
            if($User&&$session_time>$User->session_time){
                $user_id = $User->id;
                $user_level = $User->level;
                $session_time += 604800;
                $session = $this->SessionKey();
                if(!$User->save()){
                    return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
                }
            }
            return '{"user_id":'.$user_id.',"user_level":'.$user_level.',"session":"'.$session.'","session_time":"'.$session_time.'"}';
        }
        return '{"user_id":0,"user_level":0,"session":"","session_time":""}';
    }
    public function verifySession(Request $request){
        $data = $request->input();
        $code = $data['code'];
        if($code==='sessionXcx'){
            $session = $data['session'];
            $User = User::where("session",$session)->first();
            if($User){
                return $User->id;
            }
        }
        return 0;
    }
    public function GetView(Request $request){
        $data = $request->input();
        $id = $data['id'];
//        $id = 4;
        $view = Post::find($id);
        $_arr = preg_split('/(<img.*?>)/i', $view->content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
        $_r = array();
        foreach($_arr as $_txt) {
            if(substr($_txt, 0, 4) == '<img') {
                $_matchs = array();
                preg_match('/<img.*?src="(.*?)"/i', $_txt, $_matchs);
                $_txt = $_matchs[1];
                $_r[]= array('type'=>'img', 'data'=>$_txt);
            }else {
                $_r[]= array('type'=>'txt', 'data'=>$_txt);
            }
        }
        $comment = Comment::where('post_id',$id)->where('parent',0)->orderBy('id', 'desc')->get();
        $comment_id = array();
        $author = array();
        $avatar = array();
        $content = array();
        $time = array();
        $count = array();
        if($comment){
            foreach ($comment as $c){
                array_push($comment_id,$c->id);
                array_push($author,$c->name);
                array_push($content,$c->content);
                array_push($time,$c->created_at->format('Y-m-d'));
                array_push($count,Comment::where("parent",$c->id)->count());
                $a = Usermeta::where("user_id",$c->user_id)->where("key","avatar")->first();
                array_push($avatar,$a->value);
            }
        }
        $comments = array('id'=>$comment_id,'author'=>$author,'avatar'=>$avatar,'content'=>$content,'time'=>$time,'count'=>$count);
//        $likesCount = Likes::where('post_id',$id)->where('status',1)->count();
//        $likeStatus = null;
//        if($likesCount){
//            $likeStatus = Likes::where('post_id',$id)->where('user_id',$data['uid'])->where('status',1)->first();
//        }
//        $Likes = array('count'=>$likesCount,'status'=>($likeStatus?1:0));
        $con= array('title'=>$view->title,'time'=>$view->created_at->format('Y-m-d'),'author'=>$view->author,'video'=>'','content'=> $_r,'cover'=> $view->cover);
        $keepCount = Keep::where('post_id',$id)->where('status',1)->count();
        $keepStatus = null;
        if($keepCount){
            $keepStatus = Keep::where('post_id',$id)->where('user_id',$data['uid'])->where('status',1)->first();
        }
        $Keep = array('count'=>$keepCount,'status'=>($keepStatus?1:0));
        $meta = Array();
        $Postmeta = Postmeta::where("post_id",$id)->get();
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        if($data['type']=='active'){
            if(!isset($meta['viewQR'])){
                $QR = $this->getQR($id);
                if($QR){
                    $newMeta = new Postmeta();
                    $newMeta->post_id = $id;
                    $newMeta->key = 'viewQR';
                    $newMeta->value = $QR;
                    if($newMeta->save()){
                        $meta['viewQR']= $QR;
                    }
                }
            }
        }
//        $_data= array('content'=>$con,'comment'=>$comments,'likes'=>$Likes,'keep'=>($Keep?1:0),'meta'=>$meta);
        $_data= array('content'=>$con,'comment'=>$comments,'keep'=>$Keep,'meta'=>$meta);
        $view->view++;
        $view->save();
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function PostComment(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Comment = new Comment();
            $Comment->post_id = $data["id"];
            $Comment->user_id = $User->id;
            $Comment->name = $User->name;
            $Comment->content = $data["comment"];
            if($request->has('parent')){
                $Comment->parent = $data["parent"];
            }
            if($Comment->save()){
                return $Comment->id;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    public function ChangeWiget(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            if($data["type"]=="keep"){
                $Wiget = Keep::where("user_id",$data["uid"])->where("post_id",$data["id"])->first();
                if(!$Wiget){
                    $Wiget = New Keep();
                    $Wiget->user_id = $data["uid"];
                    $Wiget->post_id = $data["id"];
                }
                $Wiget->status = $data["status"];
            }else{
                $Wiget = Likes::where("user_id",$data["uid"])->where("post_id",$data["id"])->first();
                if(!$Wiget){
                    $Wiget = New Likes();
                    $Wiget->user_id = $data["uid"];
                    $Wiget->post_id = $data["id"];
                }
                $Wiget->status = $data["status"];
            }
            if($Wiget->save()){
                return $Wiget->id;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    public function GetComment(Request $request){
        $data = $request->input();
        $id = $data['id'];
        $com = Comment::find($id);

        if($com){
            $a = Usermeta::where("user_id",$com->user_id)->where("key","avatar")->first();
            $comArr = Array('id'=>$id,'author'=>$com->name,'avatar'=>$a->value,'content'=>$com->content,'time'=>$com->created_at->format('Y-m-d H:i'));

            $comments = Comment::where('parent',$id)->get();
            $comment_id = array();
            $author = array();
            $avatar = array();
            $content = array();
            $time = array();
            if($comments){
                foreach ($comments as $c){
                    array_push($comment_id,$c->id);
                    array_push($author,$c->name);
                    array_push($content,$c->content);
                    array_push($time,$c->created_at->format('Y-m-d H:i'));
                    $a = Usermeta::where("user_id",$c->user_id)->where("key","avatar")->first();
                    array_push($avatar,$a->value);
                }
            }
            $comments = array('id'=>$comment_id,'author'=>$author,'avatar'=>$avatar,'content'=>$content,'time'=>$time);
            $_data= array('content'=>$comArr,'comment'=>$comments);
            return json_encode($_data, JSON_UNESCAPED_UNICODE);
        }else{
            return 0;
        }
    }
    public function HomePage(Request $request){
        $data = $request->input();
        $type = $data["type"];
        $SwipeLength = $request->has('swipe')?$data["swipe"]:0;
        $ConId = $request->has('conId')?$data["conId"]:0;
        $TopLength= $request->has('top')?$data["top"]:0;

        $Swipe_id = Array();
        $Swipe_cover = Array();
        $Swipe_title = Array();
        $Swipe_status = Array();

        $content_id = Array();
        $content_cover = Array();
        $content_title = Array();
        $content_time = Array();
        $content_status = Array();
        $content_tag = Array();
        $content_video = Array();
        $now = time();
        if($SwipeLength == 0){
            $Swipe = Post::where("xcx",$type)->where("level",2)->where("status",1)->orderBy('id', 'desc')->get();
            if($Swipe){
                foreach ($Swipe as $s){
                    array_push($Swipe_id,$s->id);
                    array_push($Swipe_cover,$s->cover);
                    array_push($Swipe_title,$s->title);
                    array_push($Swipe_status,$this->TimeStatus($now,$s->id));
                }
            }
        }
        if($TopLength == 0){
            $TopNew = Post::where("xcx",$type)->where("level",1)->where("status",1)->orderBy('id', 'desc')->get();
            if($TopNew){
                foreach ($TopNew as $t){
                    array_push($content_id,$t->id);
                    array_push($content_cover,$t->cover);
                    array_push($content_title,$t->title);
                    array_push($content_time,$t->created_at->format('Y-m-d H:i'));
                    array_push($content_status,$this->TimeStatus($now,$t->id));
                    $Tag = Tag::find($t->tag);
                    $name = $Tag?$Tag->name:'活动路演';
                    array_push($content_tag,$name);
                    $video = Postmeta::where("post_id",$t->id)->where("key","video")->first();
                    $v = $video?1:0;
                    array_push($content_video,$v);
                }
            }
        }
        $SwipeArr = array('id'=>$Swipe_id,'pic'=>$Swipe_cover,'title'=>$Swipe_title,'status'=>$Swipe_status);

        if($ConId == 0){
            $content = Post::where("xcx",$type)->where("level",0)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
        }else{
            $content = Post::where("xcx",$type)->where("id","<",$ConId)->where("level",0)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
        }
        if($content){
            foreach ($content as $c){
                array_push($content_id,$c->id);
                array_push($content_cover,$c->cover);
                array_push($content_title,$c->title);
                array_push($content_time,$c->created_at->format('Y-m-d H:i'));
                array_push($content_status,$this->TimeStatus($now,$c->id));
                $Tag = Tag::find($c->tag);
                $name = $Tag?$Tag->name:'活动路演';
                array_push($content_tag,$name);
                $video = Postmeta::where("post_id",$c->id)->where("key","video")->first();
                $v = $video?1:0;
                array_push($content_video,$v);
            }
        }
        $conArr = array('id'=>$content_id,'pic'=>$content_cover,'title'=>$content_title,'time'=>$content_time,'status'=>$content_status,'tag'=>$content_tag,'video'=>$content_video);
        $_data= array('swipe'=>$SwipeArr,'content'=>$conArr);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function getService(Request $request){
        $data = $request->input();
        $id = $data["id"];
        $name = Array();
        $arrId = Array();
        $cover = Array();
            $Service = Tag::where('type','service')->get();
            $count = Array();
            foreach ($Service as $s){
                array_push($arrId,$s->id);
                array_push($name,$s->name);
                array_push($cover,$s->more);
                array_push($count,Post::where("tag",$s->id)->count());
            }
            $_data = Array("id"=>$arrId,"name"=>$name,"cover"=>$cover,"count"=>$count);
        if($id!=0){
            $name = Array();
            $arrId = Array();
            $cover = Array();
            $List = Post::where("tag",$id)->get();
            $metaArr = Array();
            foreach ($List as $l){
                $meta = Array();
                array_push($arrId,$l->id);
                array_push($name,$l->title);
                array_push($cover,$l->cover);
                $Postmeta = Postmeta::where("post_id",$l->id)->get();
                foreach ($Postmeta as $m){
                    $meta["$m->key"]= $m->value;
                }
                array_push($metaArr,$meta);
            }
            $_data = Array("id"=>$arrId,"name"=>$name,"cover"=>$cover,"meta"=>$metaArr,"menu"=>$_data);
        }
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function GetKeep(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        $id_a = Array();
        $pic_a = Array();
        $title_a = Array();
        $time_a = Array();
        $author_a = Array();
        $id_b = Array();
        $pic_b = Array();
        $title_b = Array();
        $time_b = Array();
        $author_b = Array();
        $id_c = Array();
        $pic_c = Array();
        $title_c = Array();
        $time_c = Array();
        $author_c = Array();
        if($User&&$User->id==$data["uid"]){
            $Tag = Tag::where("type","xcx")->get();
            $HomeNum = Array();
            $ServiceNum = Array();
            $ActiveNum = Array();
            foreach ($Tag as $t){
                if($t->name == '主页'){
                    array_push($HomeNum,$t->id);
                }elseif ($t->name == '路演'||$t->name == '活动'||$t->name == '回顾'){
                    array_push($ActiveNum,$t->id);
                }elseif ($t->name == '服务'){
                    array_push($ServiceNum,$t->id);
                }
            }
            $keep = Keep::where("status",1)->where("user_id",$User->id)->orderBy('id', 'desc')->get();
            foreach ($keep as $k){
                $Post = Post::find($k->post_id);
                if($Post){
                    if(in_array($Post->xcx,$HomeNum)){
                        array_push($id_a,$Post->id);
                        array_push($pic_a,$Post->cover);
                        array_push($title_a,$Post->title);
                        array_push($time_a,$Post->created_at->format('Y-m-d H:i'));
                        array_push($author_a,$Post->author);
                    }elseif (in_array($Post->xcx,$ActiveNum)){
                        array_push($id_b,$Post->id);
                        array_push($pic_b,$Post->cover);
                        array_push($title_b,$Post->title);
                        array_push($time_b,$Post->created_at->format('Y-m-d H:i'));
                        array_push($author_b,$Post->author);

                    }elseif (in_array($Post->xcx,$ServiceNum)){
                        array_push($id_c,$Post->id);
                        array_push($pic_c,$Post->cover);
                        array_push($title_c,$Post->title);
                        array_push($time_c,$Post->created_at->format('Y-m-d H:i'));
                        array_push($author_c,$Post->author);
                    }
                }
            }
        }
        $arr_a = Array("id"=>$id_a,"pic"=>$pic_a,"title"=>$title_a,"time"=>$time_a,"author"=>$author_a,);
        $arr_b = Array("id"=>$id_b,"pic"=>$pic_b,"title"=>$title_b,"time"=>$time_b,"author"=>$author_b,);
        $arr_c = Array("id"=>$id_c,"pic"=>$pic_c,"title"=>$title_c,"time"=>$time_c,"author"=>$author_c,);
        $_data = Array($arr_a,$arr_b,$arr_c);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function GetActive(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        $id_a = Array();
        $pic_a = Array();
        $title_a = Array();
        $time_a = Array();
        $author_a = Array();
        $cat_a = Array();
        $id_b = Array();
        $pic_b = Array();
        $title_b = Array();
        $time_b = Array();
        $author_b = Array();
        $cat_b = Array();
        if($User&&$User->id==$data["uid"]){
//        if(1){
            $Tag = Tag::where("type","xcx")->get();
            $TagNum = Array();
            $TagArr = Array();
            foreach ($Tag as $t){
                if ($t->name == '路演'||$t->name == '活动'||$t->name == '服务'){
                    $TagArr["$t->id"] = $t->name;
                    array_push($TagNum,$t->id);
                }
            }
            $Post = Post::where("user_id",1)->where(function($query) use ($TagNum){
                $query->where('xcx',$TagNum[0])
                    ->orWhere(function($query) use ($TagNum){
                        $query->where('xcx', $TagNum[1])
                            ->orWhere(function($query) use ($TagNum){
                            $query->where('xcx',$TagNum[2]);
                            });
                    });
            })->orderBy('id', 'desc')->get();
            foreach ($Post as $p){
                $now = time();
                $meta = Postmeta::where("post_id",$p->id)->where("key","activeTime")->first();
                if($meta){
                    if($p->status==1&&strtotime($meta->value)<$now){
                    array_push($id_a,$p->id);
                    array_push($pic_a,$p->cover);
                    array_push($title_a,$p->title);
                    array_push($time_a,$p->created_at->format('Y-m-d H:i'));
                    array_push($author_a,$p->author);
                    array_push($cat_a,$p->author);
                    }else{
                    array_push($id_b,$p->id);
                    array_push($pic_b,$p->cover);
                    array_push($title_b,$p->title);
                    array_push($time_b,$p->created_at->format('Y-m-d H:i'));
                    array_push($author_b,$p->author);
                    array_push($cat_b,$p->author);
                    }
                }
            }
        }
        $arr_a = Array("id"=>$id_a,"pic"=>$pic_a,"title"=>$title_a,"time"=>$time_a,"author"=>$author_a,"cat"=>$cat_a);
        $arr_b = Array("id"=>$id_b,"pic"=>$pic_b,"title"=>$title_b,"time"=>$time_b,"author"=>$author_b,"cat"=>$cat_b);
        $_data = Array($arr_a,$arr_b);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function GetMsg(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        $MsgId = Array();
        $UserName = Array();
        $time = Array();
        $content = Array();
        $parentArr = Array();
        $avatar = Array();
        $postUser = Array();
        $getUser = Array();
        if($User&&$User->id==$data["uid"]){
            if($data["parent"]==0){
//                $Msg = Message::whereRaw("get_user = ? OR post_user = ?",[$User->id,$User->id])->orderBy('id', 'desc')->get();
                $Msg = Message::where(function($query) use ($User){
                    $query->where("get_user",$User->id)
                        ->orWhere(function($query) use ($User){
                            $query->where('post_user', $User->id);
                        });
                })->orderBy('id', 'desc')->get();
            }else{
//                $Msg = Message::whereRaw("parent = ? OR id = ?",[$data["parent"],$data["parent"]])->orderBy('id', 'desc')->get();
                $Msg = Message::where(function($query) use ($data){
                    $query->where("parent",$data["parent"])
                        ->orWhere(function($query) use ($data){
                            $query->where('id', $data["parent"]);
                        });
                })->orderBy('id', 'desc')->get();
            }
            foreach ($Msg as $m){
                if($data["parent"]==0){
                    if(in_array($m->parent,$parentArr)||in_array($m->id,$parentArr)){
                        continue;
                    }else{
                        if($m->parent){
                            array_push($parentArr,$m->parent);
                        }else{
                            array_push($parentArr,$m->id);
                        }
                    }
                }
                $MsgUser = User::find($m->post_user);
                $MsgAvatar = Usermeta::where("user_id",$MsgUser->id)->where("key","avatar")->first();
                array_push($MsgId,$m->parent);
                array_push($UserName,$MsgUser?$MsgUser->name:"无此用户");
                array_push($time,$m->created_at->format('Y-m-d H:i'));
                array_push($content,$m->content);
                array_push($avatar,$MsgAvatar->value);
                array_push($postUser,$m->post_user);
                array_push($getUser,$m->get_user!=$User->id?$m->get_user:$m->post_user);
            }
        }
        $_data = Array("id"=>$MsgId,"name"=>$UserName,"time"=>$time,"content"=>$content,"avatar"=>$avatar,"postUser"=>$postUser,"getUser"=>$getUser);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function PostMsg(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Msg = new Message();
            $Msg->post_user = $User->id;
            $Msg->get_user = $data["get_user"];
            $Msg->content = $data["content"];
            $Msg->parent = $data["parent"];
            if($Msg->save()){
                return $Msg->id;
            }
        }
        return 0;
    }
    public function GetTag(){
        $Tag = Tag::where("type","tag")->get();
        $Cat = Tag::where("type","page")->get();

        $id = Array();
        $name = Array();
        foreach ($Tag as $t){
            array_push($id,$t->id);
            array_push($name,$t->name);
        }
        $TagArr = Array("id"=>$id,"name"=>$name);

        $id = Array();
        $name = Array();
        foreach ($Cat as $c){
            array_push($id,$c->id);
            array_push($name,$c->name);
        }
        $CatArr = Array("id"=>$id,"name"=>$name);
        $_data = Array("tags"=>$TagArr,"cats"=>$CatArr);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function PostActive(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $_data = json_decode($data["data"]);
            $tag = Tag::where("type","xcx")->where("name",$data["type"])->first();
            $Post = new Post();
            $Post->title = $_data->name;
            $Post->cover = asset('img/shen.jpg');
            $Post->user_id = $User->id;
            $Post->author = $User->name;
            $Post->xcx = $tag->id;
            $Post->tag = $data["cat"];
            $Post->content = $_data->content;
            $Post->status = 0;
            if($Post->save()){

                foreach($_data as $key => $value) {
                    if($key!="content"||$key!="name"){
                        $Meta = new Postmeta();
                        $Meta->post_id = $Post->id;
                        $Meta->key = $key;
                        $Meta->value = $value;
                        $Meta->save();
                    }
                }
                $tagNew = json_decode($data["arr"]);
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagNew[$i];
                    $newTag->save();
                }
                $Form = new Form();
                $Form->user_id = $User->id;
                $Form->name = $User->name;
                $Form->form = $data["data"];
                $Form->type = "active";
                $Form->status = 0;
                $Form->item = 0;
                $Form->parent = $Post->id;
                $Form->save();
                return $Post->id;
            }
        }
        return 0;
    }
    public function GetForm(Request $request){
        $data = $request->input();
        $FormItem = Formitem::find($data["id"]);
        return $FormItem->value;
    }
    public function PostForm(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Form = new Form();
            $Form->user_id = $User->id;
            $Form->name = $User->name;
            if(isset($data["info"])){
                $arr = Array();
                array_push($arr,$User->name);
                array_push($arr,$User->phone);
                $Form->form = json_encode($arr, JSON_UNESCAPED_UNICODE);
            }else{
                $Form->form = $data["data"];
            }
            $Form->type = $data["type"];
            $Form->status = 0;
            $Form->parent = $data["parent"];
            $Form->item = $data["id"];
            if($User->level==0&&isset($data["phone"])){
                $User->level=2;
                $User->phone=$data["phone"];
                $User->save();
            }
            if($Form->save()){
                if(isset($data["info"])){
                    return $User->phone;
                }
                return $Form->id;
            }
        }
        return 0;
    }
    public function HomeService(){
        $id = [15,14,16];
        $num = Array();
        for ($i=0;$i<3;$i++){
            $n = Post::where("tag",$id[$i])->count();
            array_push($num,$n);
        }
        $Swipe_id = Array();
        $Swipe_cover = Array();
        $Swipe_title = Array();
        $Swipe = Post::where("xcx",1)->where("level",2)->where("status",1)->orderBy('id', 'desc')->get();
        if($Swipe){
            foreach ($Swipe as $s){
                array_push($Swipe_id,$s->id);
                array_push($Swipe_cover,$s->cover);
                array_push($Swipe_title,$s->title);
            }
        }
        $SwipeArr = array('id'=>$Swipe_id,'pic'=>$Swipe_cover,'title'=>$Swipe_title);
        $_data= array('swipe'=>$SwipeArr,'num'=>$num);
        return $_data;
    }
    public function SMS(Request $request){
        $data = $request->input();
        $User = User::where("session",$data["session"])->first();
        if($User&&$User->id==$data["uid"]){
            $Phone = $data["Phone"];
            $code = $this->RandomString();
            $arr = [$code,"5"];
            $SMS = new SendTemplateSMS();
            $msg = $SMS->SendSMS($Phone,$arr,'158289');
            if($msg){
                return $code;
            }
        }
        return 0;
    }
    public function GetNews(Request $request){
        $data = $request->input();
        $type = $data["type"];
        $ConId = $request->has('conId')?$data["conId"]:0;
        $TopLength= $request->has('top')?$data["top"]:0;
        $MenuLength = $request->has('menu')?$data["menu"]:0;

        $Menu_id = Array();
        $Menu_name = Array();

        $content_id = Array();
        $content_cover = Array();
        $content_title = Array();
        $content_time = Array();
        $content_author = Array();

        if($MenuLength == 0){
            $Menu = Tag::where("type","page")->get();
            if($Menu){
                foreach ($Menu as $m){
                    array_push($Menu_id,$m->id);
                    array_push($Menu_name,$m->name);
                }
            }
        }
        $MenuArr = array('id'=>$Menu_id,'name'=>$Menu_name);

        $TopNew = 0;
        if($type == 0){
            if($TopLength == 0){
                $TopNew = Post::where("xcx",1)->where("level",1)->where("status",1)->orderBy('id', 'desc')->get();
            }

            if($ConId == 0){
                $content = Post::where("xcx",1)->where("level","<>",1)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
            }else{
                $content = Post::where("xcx",1)->where("id","<",$ConId)->where("level","<>",1)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
            }
        }else{
            if($TopLength == 0){
                $TopNew = Post::where("xcx",1)->where("tag",$type)->where("level",1)->where("status",1)->orderBy('id', 'desc')->get();
            }

            if($ConId == 0){
                $content = Post::where("xcx",1)->where("tag",$type)->where("level","<>",1)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
            }else{
                $content = Post::where("xcx",1)->where("tag",$type)->where("id","<",$ConId)->where("level","<>",1)->where("status",1)->orderBy('id', 'desc')->simplePaginate(20);
            }
        }
        if($TopNew){
            foreach ($TopNew as $t){
                array_push($content_id,$t->id);
                array_push($content_cover,$t->cover);
                array_push($content_title,$t->title);
                array_push($content_time,$t->created_at->format('Y-m-d H:i'));
                array_push($content_author,$t->author);
            }
        }
        if($content){
            foreach ($content as $c){
                array_push($content_id,$c->id);
                array_push($content_cover,$c->cover);
                array_push($content_title,$c->title);
                array_push($content_time,$c->created_at->format('Y-m-d H:i'));
                array_push($content_author,$c->author);
            }
        }
        $conArr = array('id'=>$content_id,'pic'=>$content_cover,'title'=>$content_title,'time'=>$content_time,'author'=>$content_author);
        $_data= array('menu'=>$MenuArr,'content'=>$conArr);
        return json_encode($_data, JSON_UNESCAPED_UNICODE);
    }
    public function FY(Request $request){
        $data = $request->input();
        $phone = $data["phone"];
        $id = $data["id"];
        $ret = null;

        $feiyuApi = new FeiyuApi();
        $ret = $feiyuApi->callBackUrlAction($id,'86'.$phone);
        return $ret;

    }
}
